<template>
  <div class="devicemgrpanel-container">
    <h1>设备管理</h1>
    <el-divider></el-divider>
    <el-row :gutter="20">
      <el-col :span="6">
        <div>
          <span class="input-text">设备ID</span>
          <el-input class="input-textfeild" placeholder="请输入设备ID" v-model="addDeviceData.deviceID"></el-input>
        </div>
      </el-col>
      <el-col :span="6">
        <span class="input-text">设备描述</span>
        <el-input class="input-textfeild" placeholder="请输入设备描述" v-model="addDeviceData.address"></el-input>
      </el-col>
      <el-col :span="6">
        <el-button style="margin: 5px" type="primary" @click="handleAdd(addDeviceData)">添加设备</el-button>
      </el-col>
    </el-row>
    <el-divider></el-divider>
    <el-table
      :data="curTableData"
      style="width: 100%"
    >
      /* 第一列 */
      <el-table-column label="设备ID" width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.deviceID }}</span>
        </template>
      </el-table-column>
      /* 第二列 */
      <el-table-column label="设备描述" width="420">
        <template slot-scope="scope">
          <el-input v-model="scope.row.address" :disabled="scope.row.disabled" style="width: 100%"></el-input>
        </template>
      </el-table-column>
      /* 第三列 */
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">{{ scope.row.btnText }}</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      background
      layout="prev, pager, next"
      :total="totalItems"
    ></el-pagination>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { deviceAdd, deviceDel, initDevices, unserializer, deviceEdit } from '@/views/devicemgrpanel/devicemgrpanel'

export default {
  name: 'DeviceMgrPanel',
  components: {},
  props: {},
  data() {
    return {
      /* 添加变量 */
      addDeviceData: {
        deviceID: '',
        address: ''
      },
      /* 表格数据绑定变量 */
      tableData: [],
      /* 当前页 */
      currentPage: 1,
      pageSize: 3,
      totalItems: 0,
      curTableData: []
    }
  },
  computed: {},
  watch: {},
  created() {
  },
  mounted() {
    /* 获取设备列表 */
    this.initTableData()
    /* 初始化翻页控件参数 */
    this.totalItems = this.tableData.length
    this.curTableData = this.tableData.slice(0, this.currentPage * this.pageSize)
  },
  methods: {
    handleEdit(index, row) {
      // *这里可以不用换算成tableData的真实index, row似乎已经绑定到特定的控件上了
      if (row.disabled) {
        // 编辑模式，按钮显示为‘保存’
        row.disabled = false
        row.btnText = '保存'
      } else {
        // 保存编辑模式，按钮显示为‘编辑’
        row.disabled = true
        row.btnText = '编辑'
        // todo: 此处编辑要与服务器同步
        return new Promise((resolve, reject) => {
          deviceEdit({ deviceID: row.deviceID, description: row.address }).then(response => {
            const data = response
            if (data.opcode === 1) {
              // 修改成功
              this.tableData = unserializer(data.devices)
              this.refreshCurTableData() // 因为这是一个异步请求，所以请求回来后要刷新实例绑定的数据
            } else {
              this.$notify({ title: '提示', message: '修改失败', duration: 1500 })
            }
            resolve()
          }).catch(error => {
            this.$notify({ title: '提示', message: '修改失败', duration: 1500 })
            reject(error)
          })
        })
      }
      this.refreshCurTableData()
    },
    handleDelete(index, row) {
      console.log(index, row)
      // 换算table的真实index
      const index_t = (this.currentPage - 1) * this.pageSize + index
      this.tableData.splice(index_t, 1)
      // todo: 此处删除要与服务器同步
      return new Promise((resolve, reject) => {
        deviceDel({ deviceID: row.deviceID }).then(response => {
          const data = response
          if (data.opcode === 1) {
            // 删除成功
            this.tableData = unserializer(data.devices)
            this.refreshCurTableData() // 因为这是一个异步请求，所以请求回来后要刷新实例绑定的数据
          } else {
            this.$notify({ title: '提示', message: '删除失败', duration: 1500 })
          }
          resolve()
        }).catch(error => {
          this.$notify({ title: '提示', message: '服务器无响应，稍后重试', duration: 1500 })
          reject(error)
        })
      })
    },
    handleAdd(addDeviceData) {
      // todo: 此处应先与服务通信，在服务器有响应时再添加
      return new Promise((resolve, reject) => {
        deviceAdd({
          deviceID: addDeviceData.deviceID,
          address: addDeviceData.address
        }).then(response => {
          const data = response
          if (data.opcode === 1) {
            // 成功
            /* 反序列化 */
            this.tableData = unserializer(data.devices)
            this.refreshCurTableData()
          } else {
            // 失败
            // todo: 失败提示
            this.$notify({ title: '提示', message: '添加失败', duration: 1500 })
          }
          resolve()
        }).catch(error => {
          this.$notify({ title: '提示', message: '服务器无响应，稍后重试', duration: 1500 })
          reject(error)
        })
      })
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.refreshCurTableData()
    },
    refreshCurTableData() {
      this.totalItems = this.tableData.length
      console.log('refreshCurTableData', this.currentPage)
      if (Math.ceil(this.totalItems / this.pageSize) < this.currentPage) {
        // 当前页不足
        this.currentPage -= 1
        this.currentPage = Math.max(this.currentPage, 1)
      }
      const start = this.currentPage - 1
      this.curTableData = this.tableData.slice(start * this.pageSize, (start + 1) * this.pageSize)
    },
    initTableData() {
      return new Promise((resolve, reject) => {
        initDevices().then(response => {
          const data = response
          /* 反序列化 */
          this.tableData = unserializer(data.devices)
          this.refreshCurTableData() // 因为这是一个异步请求，所以请求回来后要刷新实例绑定的数据
          resolve()
        }).catch(error => {
          this.$notify({ title: '提示', message: '服务器无响应，稍后重试', duration: 1500 })
          reject(error)
        })
      })
    }
  }
}
</script>

<style  lang="scss" scoped>
.devicemgrpanel {
  &-container {
    margin: 30px
  }
}
  /* 去掉最下面的那一条线 */
.el-table::before {
  height: 0px
}
.input {
  &-text {
    margin: 5px;
    width: 25%;
  }
  &-textfeild {
    position: relative;
    font-size: 14px;
    margin: 5px;
    width: 75%;
    display: inline-block;
  }
}
</style>
